package com.zilla.android.lib.ui.photo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import com.zilla.android.lib.ui.photo.util.FileUtils;
import com.zilla.android.lib.ui.photo.util.ImageUtils;
import com.zilla.android.lib.ui.photo.util.MediaUtils;
import com.zilla.android.zillacore.libzilla.file.FileHelper;
import com.zilla.android.zillacore.libzilla.file.PropertiesManager;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: chenze
 * Date: 13-11-19
 * Time: 下午10:06
 * To change this template use File | Settings | File Templates.
 */
public class PhotoOperator {

    private Activity activity;
    private Fragment fragment;
    private IPhotoCallback iPhotoCallback;
    private String cameraPath = "";
    private int imgsize = 800;

    public PhotoOperator(Activity activity, Fragment fragment) {
        this.activity = activity;
        this.fragment = fragment;
        if(activity == null){
            activity = fragment.getActivity();
        }
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1 && msg.obj != null) {
                String filePaht = (String) msg.obj;
                if (iPhotoCallback != null) {
                    iPhotoCallback.onPhotoGet(filePaht);
                }
            }
        }
    };

    /**
     * 转到拍照页面
     */
    public void doCamera() {
        String savePath = "";
        //判断是否挂载了SD卡
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            savePath = FileHelper.PATH_CACHE + "Camera";
            File savedir = new File(savePath);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        }
        //没有挂载SD卡，无法保存文件
        if (TextUtils.isEmpty(savePath)) {
            //UIHelper.ToastMessage(LifePutActivity.this, "无法保存照片，请检查SD卡是否挂载");
            return;
        }
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String fileName = PropertiesManager.getInstance().get("cache", "") + "_" + timeStamp + ".jpg";//照片命名
        File out = new File(savePath, fileName);
        Uri uri = Uri.fromFile(out);
        cameraPath = savePath + fileName;//该照片的绝对路径
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        if (activity != null) {
            activity.startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
        } else if (fragment != null) {
            fragment.startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
        }

    }

    /**
     * 选择图片
     */
    public void doPhoto() {
        //手机选图
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        if (activity != null) {
            activity.startActivityForResult(Intent.createChooser(intent, "选择图片"), ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
        } else if (fragment != null) {
            fragment.startActivityForResult(Intent.createChooser(intent, "选择图片"), ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
        }

    }

    public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        String resultPath = "";

        if (resultCode != Activity.RESULT_OK) return;
        new Thread() {
            public void run() {
                Bitmap bitmap = null;
                File imgFile = null; //小图文件
                String theThumbnail = "";
                if (requestCode == ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD) {
                    if (data == null) return;

                    Uri thisUri = data.getData();
                    String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(thisUri);

                    //如果是标准Uri
                    if (TextUtils.isEmpty(thePath)) {
                        cameraPath = ImageUtils.getAbsoluteImagePath(activity, thisUri);
                    } else {
                        cameraPath = thePath;
                    }
//                    if(TextUtils.isEmpty(cameraPath)){
//                        try{
//                            cameraPath = com.ipaulpro.afilechooser.utils.FileUtils.getFile(thisUri).getAbsolutePath();
//                        }catch (Exception e){
//                            e.printStackTrace();
//                        }
//                    }
                    String attFormat = FileUtils.getFileFormat(cameraPath);
                    if (!"photo".equals(MediaUtils.getContentType(attFormat))) {
                        //Toast.makeText(LifePutActivity.this, getString(R.string.choose_image), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    //获取图片缩略图 只有Android2.1以上版本支持
                    /*if(AppContext.isMethodsCompat(android.os.Build.VERSION_CODES.ECLAIR_MR1)){
                        String imgName = FileUtils.getFileName(theLarge);
		    			bitmap = ImageUtils.loadImgThumbnail(LifePutActivity.this, imgName, MediaStore.Images.Thumbnails.MICRO_KIND);
		    		}*/

                    if (bitmap == null && !TextUtils.isEmpty(cameraPath)) {
                        bitmap = ImageUtils.loadImgThumbnail(cameraPath, 100, 100);
                    }
                }
                //拍摄图片
                else if (requestCode == ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA) {
                    if (bitmap == null && !TextUtils.isEmpty(cameraPath)) {
                        bitmap = ImageUtils.loadImgThumbnail(cameraPath, 100, 100);
                    }
                }

                if (bitmap != null) {
                    //存放照片的文件夹
                    String savePath = FileHelper.PATH_CACHE + "Camera";
                    ;
                    File savedir = new File(savePath);
                    if (!savedir.exists()) {
                        savedir.mkdirs();
                    }

                    String largeFileName = FileUtils.getFileName(cameraPath);
                    String largeFilePath = savePath + largeFileName;
                    //判断是否已存在缩略图
                    if (largeFileName.startsWith("thumb_") && new File(largeFilePath).exists()) {
                        theThumbnail = largeFilePath;
                        imgFile = new File(theThumbnail);
                    } else {
                        //生成上传的800宽度图片
                        theThumbnail = "thumb_" + largeFileName;
                        theThumbnail = savePath + theThumbnail;
                        if (new File(theThumbnail).exists()) {
                            imgFile = new File(theThumbnail);
                        } else {
                            try {
                                //压缩上传的图片
                                ImageUtils.createImageThumbnail(activity, cameraPath, theThumbnail, imgsize, 80);
                                imgFile = new File(theThumbnail);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    Message msg = new Message();
                    msg.what = 1;
//					msg.obj = bitmap;
                    if (!TextUtils.isEmpty(theThumbnail)) {
                        msg.obj = theThumbnail;
                    } else {
                        msg.obj = largeFileName;
                    }
                    handler.sendMessage(msg);
                }
            }

            ;
        }.start();
    }

    public int getImgsize() {
        return imgsize;
    }

    public void setImgsize(int imgsize) {
        this.imgsize = imgsize;
    }

    public IPhotoCallback getiPhotoCallback() {
        return iPhotoCallback;
    }

    public void setiPhotoCallback(IPhotoCallback iPhotoCallback) {
        this.iPhotoCallback = iPhotoCallback;
    }

    /**
     * 图片回调
     */
    public interface IPhotoCallback {
        /**
         * 图片地址回调
         *
         * @param path
         */
        void onPhotoGet(String path);
    }
}
